package com.cac.demo.controller.mscarbasic;

import com.alibaba.fastjson.JSON;
import com.cac.demo.entity.mscarbasic.MsCarBasicDTO;
import com.cac.demo.service.mscarbasic.MsCarBasicService;
import com.cac.demo.util.adapter.*;
import com.fasterxml.jackson.core.type.TypeReference;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.cac.demo.util.adapter.BusinessUtil.getSortExpColumnName;


@RestController
@Api(tags = "配送小车信息接口")
@RequestMapping("/mscar/")
public class MsCarBasicRest {
    @Autowired
    private MsCarBasicService msCarBasicService;

    /**
     * 按条件分页查询
     * @param map
     * @return
     */
    @PostMapping("/searchByPage")
    @ApiOperation(value = "按条件分页查询")
    public ResponseMsg<QueryRespBean<HashMap>> searchByPage(@ApiParam(value = "查询条件" , name = "queryReqBean")@RequestBody Map map   ){
        ResponseMsg<QueryRespBean<HashMap>> responseMsg = new ResponseMsg<>();
        //分页
        String param = JSON.toJSONString(map.get("pageParameter"));
        PageParameter pageParameter = JSON.parseObject(param, PageParameter.class);
        //查询条件
        String searchParamsParams = JSON.toJSONString(map.get("searchParams"));
        HashMap searchParams = JSON.parseObject(searchParamsParams, HashMap.class);

        QueryReqBean<HashMap> queryReqBean = new QueryReqBean<>();
        queryReqBean.setSearchParams(searchParams);
        queryReqBean.setPageParameter(pageParameter);

        if (StringUtils.hasText(queryReqBean.getSidx()) && StringUtils.hasText(queryReqBean.getSord())) {
            String sordExp = getSortExpColumnName(queryReqBean.getSidx(), queryReqBean.getSord(), MsCarBasicDTO.class);
            if (StringUtils.hasText(sordExp)) {
                queryReqBean.setSortExp(sordExp);
            }
        }
        if (StringUtils.hasText(queryReqBean.getKeyWord())) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            HashMap searchKeyWordParam = JsonHelper.getInstance().readValue(queryReqBean.getKeyWord(), dateFormat, new TypeReference<HashMap>() {
            });
            queryReqBean.setSearchParams(searchKeyWordParam);
        }
        QueryRespBean<HashMap> result = msCarBasicService.searchMsCarBasicByPage(queryReqBean, ContextCommonHolder.getOrgId(),queryReqBean.getSortExp());
        List<HashMap> result1 = msCarBasicService.searchMsCarBasicByPage(searchParams, ContextCommonHolder.getOrgId(),queryReqBean.getSortExp());
        if(result1.size()!=0){
            responseMsg.setResponseBody(result).setRetCode("200");
        }
        else responseMsg.setRetCode("201").setMessage("未查询到数据").setResponseBody(result);
        return responseMsg;

    }
    /**
     * 根据条件查询数据
     * @param queryReqBean
     * @return
     */
    @RequestMapping("/searchByParams")
    @ApiOperation(value = "根据条件查询数据")
    public ResponseMsg<List<MsCarBasicDTO>> searchByParams(@ApiParam(value = "查询条件" ,name = "queryReqBean" )@RequestBody QueryReqBean<MsCarBasicDTO> queryReqBean){
        ResponseMsg<List<MsCarBasicDTO>> responseMsg = new ResponseMsg<>();
        List<MsCarBasicDTO> result = msCarBasicService.searchMsCarByParams(queryReqBean);
        responseMsg.setResponseBody(result);
        return  responseMsg;
    }
    /**
     * 通过主键查询单条记录
     *
     * @param id 主键id
     * @return ResponseMsg<MsCarBasicDTO>
     */
    @GetMapping("/get/v1/{id}")
    @ApiOperation(value = "通过主键查询单条记录")
    public ResponseMsg<MsCarBasicDTO> get(@ApiParam(value = "")@PathVariable("id") String id) {
        ResponseMsg<MsCarBasicDTO> responseMsg = new ResponseMsg<>();
        MsCarBasicDTO msCarBasicDTO = msCarBasicService.findMsCarBasicById(id);
        if (msCarBasicDTO != null) {
            //valueConvert(Arrays.asList(employeeBasic1));
        }
        responseMsg.setResponseBody(msCarBasicDTO);
        return responseMsg;
    }
    /**
     * 批量新增数据
     */
    @PostMapping("/save")
    @ApiOperation(value = "批量新增数据")
    public ResponseMsg<Map> saveMany(@ApiParam(value = "待新增数据集" ,name = "msMsCarBasicDTOS")@RequestBody HashMap<String, Object> map){
        ResponseMsg<Map> responseMsg =  new ResponseMsg<>();
        Map reMsg = new HashMap();
        int carCodeCount = msCarBasicService.queryCarCode(map.get("carCode").toString());
        if (carCodeCount>0)
        {
            responseMsg.setRetCode("201");
            responseMsg.setMessage("已存在该小车编号："+map.get("carCode").toString()+"！");
            return responseMsg;
        }
        int s = 0;
        int f = 0;
        try {
            msCarBasicService.insertMsCarBasic(map);
            s++;
        }catch(Exception e)
        {
            e.printStackTrace();
            f++;
        }
        reMsg.put("成功：", s);
        reMsg.put("失败：", f);
        if (s == 0 && f != 0) {
            responseMsg.setRetCode("201");
            responseMsg.setMessage("新增失败！");

        }
        if (s != 0 && f == 0) {
            responseMsg.setRetCode("200");
            responseMsg.setMessage("新增成功！");
        }
        return responseMsg;
    }
    /**
     * 批量修改数据
     * @param
     * @return
     */
    @PostMapping("/update")
    @ApiOperation(value = "批量修改数据")
    public ResponseMsg<Map> updateMany(@ApiParam(value = "需要修改数据集" ,name = "msMsCarBasicDTOS")@RequestBody HashMap<String, Object> map){
        ResponseMsg<Map> responseMsg = new ResponseMsg<>();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String account = (String) request.getSession().getAttribute("account");
        String IP = null;

        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }

        map.put("lastUpdatedBy",account);
        map.put("lastUpdateIp",IP);
        Map reMsg = new HashMap();
        int s = 0;
        int f = 0;
        if(map.get("msCarId")!= null){
            try {
                msCarBasicService.updateMsCarBasic(map);
                s++;
            }catch(Exception e)
            {
                e.printStackTrace();
                f++;
            }
        }
        else f++;
        reMsg.put("成功：", s);
        reMsg.put("失败：", f);
        if (s == 0 && f != 0) {
            responseMsg.setRetCode("201");
            responseMsg.setMessage("修改失败！");

        }
        if (s != 0 && f == 0) {
            responseMsg.setRetCode("200");
            responseMsg.setMessage("修改成功！");
        }
        return responseMsg;
    }
    /**
     * 批量删除
     *
     * @param map
     * @return ResponseMsg<Integer>
     */
    @PostMapping("/deleteById")
    @ApiOperation(value = "批量删除数据")
    public ResponseMsg<Map> deleteByIds(@ApiParam(value = "被删数据主键ID集" ,name = "ids")@RequestBody HashMap<String, Object> map) {
        ResponseMsg<Map> responseMsg = new ResponseMsg<>();
        Map reMsg = new HashMap();
        int s = 0;
        int f = 0;
        List<HashMap<String, Object>> ids = (List<HashMap<String, Object>>) map.get("data");
        if(ids.size()==0){
            return responseMsg.setRetCode("201").setMessage("请选择需要删除的数据");
        }
        for(int i = 0 ;i<ids.size();i++){
            HashMap<String, Object> map1 = ids.get(i);
            String id = (String) map1.get("msCarId");
            if(map1.get("msCarId")!=null){
                msCarBasicService.deleteMsCarBasicById(id);
                s++;
            }
            else f++;
        }
        reMsg.put("成功：", s);
        reMsg.put("失败：", f);
        if (s == 0 && f != 0) {
            responseMsg.setRetCode("201");
            responseMsg.setMessage("删除失败！");

        }
        if (s != 0 && f == 0) {
            responseMsg.setRetCode("200");
            responseMsg.setMessage("删除成功！");
        }
        if (s != 0 && f != 0) {
            responseMsg.setRetCode("202");
            responseMsg.setMessage("删除有失败项！");
            responseMsg.setResponseBody(reMsg);
        }
        return responseMsg;
    }
}
